using IGeekFan.AspNetCore.Knife4jUI;
using Microsoft.Extensions.FileProviders;
using System.Reflection;
using WorkflowCore.Interface;
using Yitter.IdGenerator;
using Yuekao.API.Write;
using Yuekao.API.Write.CommandHander;

//using Yuekao.API.Write.CommandHander;
using Yuekao.Domain;
using Yuekao.Domain.BaseReposi;
using Yuekao.Domain.Entitys;
using Yuekao.Domain.Step;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

//����ע��
builder.Services.AddSwaggerGen(x=>
{
    var path=AppDomain.CurrentDomain.BaseDirectory+ "Yuekao.API.Write.xml";
    x.IncludeXmlComments(path,true);
});


//builder.Services.AddScoped<DefinitionAddCommandHandler>();

//�н���
builder.Services.AddMediatR(x=>x.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));

//���ù����ִ�
builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
//mapper
builder.Services.AddAutoMapper(typeof(Mymapper));
#region  ������

//������
builder.Services.AddDbContext<WorkflowContext>();

//�������ݿ�
builder.Services.AddWorkflow(x =>
{
    x.UseMySQL(builder.Configuration.GetConnectionString("MySQL"),false,false);
});

//ע�Ჽ��
builder.Services.AddScoped<StartStep>();
builder.Services.AddScoped<AuditStep>();
builder.Services.AddScoped<EndStep>();


//Json������
builder.Services.AddWorkflowDSL();

#endregion

//ѩ��id
YitIdHelper.SetIdGenerator(new IdGeneratorOptions(0));

var app = builder.Build();


app.UseSwagger();
//app.UseSwaggerUI();
app.UseKnife4UI();

// 启动工作流主机并加载已存在的工作流定义
var workflowHost = app.Services.GetRequiredService<IWorkflowHost>();
workflowHost.Start();

// 加载数据库中已存在的工作流定义
using (var scope = app.Services.CreateScope())
{
    var repository = scope.ServiceProvider.GetRequiredService<IBaseRepository<WorkflowDefinitionModel>>();
    var definitionLoader = scope.ServiceProvider.GetRequiredService<IDefinitionLoader>();
    var workflowRegistry = scope.ServiceProvider.GetRequiredService<IWorkflowRegistry>();
    
    var definitions = repository.GetAll().ToList();
    foreach (var definition in definitions)
    {
        if (!workflowRegistry.IsRegistered(definition.DefinitionId, definition.Version))
        {
            var handler = new DefinitionAddCommandHandler(repository, definitionLoader, workflowRegistry);
            handler.Location(definition);
        }
    }
}

// 启用静态文件服务
app.UseStaticFiles();

// 配置静态文件路由，使上传的图片可以直接访问
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.WebRootPath, "uploads")),
    RequestPath = "/uploads"
});

//
app.UseCors(x=>x.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());

app.UseAuthorization();

app.MapControllers();

app.Run();
